/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.service.*;
import me.zhengjie.modules.system.domain.vo.CoursechapterQueryCriteria;
import lombok.RequiredArgsConstructor;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.*;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.zhengjie.utils.PageResult;
import me.zhengjie.modules.system.domain.Coursechapterauditlog;

import static me.zhengjie.utils.TreeDataUtil.convertObjectToMap;

/**
* @author shitou
* @date 2024-12-12
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "课程章节管理")
@RequestMapping("/api/coursechapter")
public class CoursechapterController {

    private final CoursechapterService coursechapterService;

    private final CoursechapterauditlogService coursechapterauditlogService;

    private final CoursechapterresourcesService coursechapterresourcesService;

    private final CoursechapterexercisesetService coursechapterexercisesetService;

    private final CourseteacherService courseteacherService;

    private final TeacherService teacherService;
    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
//    @PreAuthorize("@el.check('coursechapter:list')")
    public void exportCoursechapter(HttpServletResponse response, CoursechapterQueryCriteria criteria) throws IOException {
        coursechapterService.download(coursechapterService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询课程章节")
    @ApiOperation("查询课程章节")
//    @PreAuthorize("@el.check('coursechapter:list')")
    public ResponseEntity<List<Map<String, Object>>> queryCoursechapter(CoursechapterQueryCriteria criteria){

        List<Coursechapter> list2 = coursechapterService.queryAll(criteria);
        List<Integer> courseChapterIds = new ArrayList<>();
        for(Coursechapter coursechapter:list2){
            courseChapterIds.add(coursechapter.getId());
        }
        if(courseChapterIds.size()!=0){
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.in("courseChapterId",courseChapterIds);
            List<Courseteacher> courseteacherList = courseteacherService.list(queryWrapper);
            List<Integer> teacherIds = new ArrayList<>();
            for(Courseteacher courseteacher:courseteacherList){
                teacherIds.add(courseteacher.getTeacherId());
            }
            if(teacherIds.size()!=0){
                QueryWrapper queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.in("id",teacherIds);
                List<Teacher> teacherList = teacherService.list(queryWrapper2);

                for(Coursechapter coursechapter:list2){
                    List<Teacher> teacherList1 = new ArrayList<>();
                    for(Courseteacher courseteacher:courseteacherList){
                        if(coursechapter.getId() == courseteacher.getCourseChapterId()){
                            for(Teacher teacher:teacherList){
                                if(courseteacher.getTeacherId() ==Math.toIntExact(teacher.getId())){
                                    teacherList1.add(teacher);
                                }
                            }
                        }
                    }
                    coursechapter.setTeacherList(teacherList1);
                }
            }


            QueryWrapper queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.in("courseChapterId",courseChapterIds);
            List<Coursechapterauditlog> courseChapterAuditLogList = coursechapterauditlogService.list(queryWrapper1);

            for(Coursechapter coursechapter :list2){
                for(Coursechapterauditlog courseChapterAuditLog:courseChapterAuditLogList){
                    if(coursechapter.getId() == courseChapterAuditLog.getCourseChapterId()){
                        coursechapter.setRejectData(courseChapterAuditLog.getContent());
                    }
                }
            }
        }
        List<Map<String,Object>> list4 = new ArrayList<>();
        for(Coursechapter coursechapter :list2){
            Map<String, Object> map = convertObjectToMap(coursechapter);
            map.put("id",coursechapter.getId());
            map.put("children",new ArrayList<>());
            map.put("parentId",coursechapter.getParentId());
            map.put("courseId",coursechapter.getCourseId());
            map.put("rejectData",coursechapter.getRejectData());
            list4.add(map);
        }

        List<Map<String,Object>> list5 = list4.stream().filter(m -> (m.get("parentId") + "").equals("0")).peek(
                (m) -> m.put("children", getChildren(m,list4))
        ).collect(Collectors.toList());
        return new ResponseEntity<>(list5,HttpStatus.OK);
    }

    @GetMapping("/getTeacherCourseChapter")
    @Log("查询课程章节")
    @ApiOperation("查询课程章节")
    public ResponseEntity<List<Map<String, Object>>> getTeacherCourseChapter(CoursechapterQueryCriteria criteria){


        criteria.setState(2);
        List<Coursechapter> list2 = coursechapterService.getTeacherCourseChapter(criteria);
        List<Map<String,Object>> list4 = new ArrayList<>();
        for(Coursechapter coursechapter :list2){
            Map<String, Object> map = convertObjectToMap(coursechapter);
            map.put("id",coursechapter.getId());
            map.put("children",new ArrayList<>());
            map.put("parentId",coursechapter.getParentId());
            map.put("courseId",coursechapter.getCourseId());
            list4.add(map);
        }

        List<Map<String,Object>> list5 = list4.stream().filter(m -> (m.get("parentId") + "").equals("0")).peek(
                (m) -> m.put("children", getChildren(m,list4))
        ).collect(Collectors.toList());
        return new ResponseEntity<>(list5,HttpStatus.OK);
    }

    @GetMapping("/getEditCourseChapter")
    @Log("查询课程章节")
    @ApiOperation("查询课程章节")
    public ResponseEntity<List<Map<String, Object>>> getEditCourseChapter(CoursechapterQueryCriteria criteria){
        criteria.setState(2);
        List<Coursechapter> list2 = coursechapterService.queryAll(criteria);
        List<Map<String,Object>> list4 = new ArrayList<>();
        for(Coursechapter coursechapter :list2){
            Map<String, Object> map = convertObjectToMap(coursechapter);
            map.put("id",coursechapter.getId());
            map.put("children",new ArrayList<>());
            map.put("parentId",coursechapter.getParentId());
            map.put("courseId",coursechapter.getCourseId());
            list4.add(map);
        }

        List<Map<String,Object>> list5 = list4.stream().filter(m -> (m.get("parentId") + "").equals("0")).peek(
                (m) -> m.put("children", getChildren(m,list4))
        ).collect(Collectors.toList());
        return new ResponseEntity<>(list5,HttpStatus.OK);
    }


    public static List<Map<String,Object>> getChildren(Map<String,Object> root, List<Map<String,Object>> all){
        List<Map<String,Object>> list1 = all.stream().filter(m -> Objects.equals(m.get("parentId"),root.get("id"))).peek(
                (m) -> m.put("children",(getChildren(m,all)))
        ).collect(Collectors.toList());
        return list1;
    }
    @PostMapping
    @Log("新增课程章节")
    @ApiOperation("新增课程章节")
//    @PreAuthorize("@el.check('coursechapter:add')")
    public ResponseEntity<Object> createCoursechapter(@Validated @RequestBody Coursechapter resources){
        coursechapterService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改课程章节")
    @ApiOperation("修改课程章节")
//    @PreAuthorize("@el.check('coursechapter:edit')")
    public ResponseEntity<Object> updateCoursechapter(@Validated @RequestBody Coursechapter resources){
        coursechapterService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @PutMapping("/auditCoursechapter")
//    @Log("修改课程章节")
//    @ApiOperation("修改课程章节")
//    @PreAuthorize("@el.check('coursechapter:edit')")
    public ResponseEntity<Object> auditCoursechapter(@RequestBody Map<String,Object> objectMap){

        Coursechapter coursechapter = coursechapterService.getById((Integer) objectMap.get("id"));
        coursechapter.setState((Integer) objectMap.get("state"));
        coursechapterService.update(coursechapter);

        Coursechapterauditlog coursechapterauditlog = new Coursechapterauditlog();
        coursechapterauditlog.setContent((String) objectMap.get("content"));
        coursechapterauditlog.setCourseId(coursechapter.getCourseId());
        coursechapterauditlog.setCourseChapterId((Integer) objectMap.get("id"));
        coursechapterauditlog.setState((Integer) objectMap.get("state"));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 生成时间戳
        String timestamp = sdf.format(new Date());
        coursechapterauditlog.setCreateTime(timestamp);
        coursechapterauditlogService.create(coursechapterauditlog);
        Map<String,String> map = new HashMap<>();
        map.put("code","0");
        return new ResponseEntity<>(map,HttpStatus.OK);
    }

    @DeleteMapping
    @Log("删除课程章节")
    @ApiOperation("删除课程章节")
//    @PreAuthorize("@el.check('coursechapter:del')")
    public ResponseEntity<Object> deleteCoursechapter(@RequestBody List<Integer> ids) {
//        查询所有删除id的父级
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",ids);
        List<Coursechapter> coursechapterList = coursechapterService.list(queryWrapper);

        for(Integer i=0;i<coursechapterList.size();i++){
            ids.add(coursechapterList.get(i).getId());
        }
        //删除课程章节
        QueryWrapper queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.in("id",ids);
        coursechapterService.remove(queryWrapper3);
        //删除课程章节资源
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("courseChapterId",ids);
        coursechapterresourcesService.remove(queryWrapper1);
        //删除课程章节习题
        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("courseChapterId",ids);
        coursechapterexercisesetService.remove(queryWrapper2);
//        coursechapterService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}